package com.zhuchaooasystem.api;

import android.app.Activity;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;

import com.zhuchaooasystem.common.Constants;
import com.zhuchaooasystem.common.Key;
import com.zhuchaooasystem.utils.BitmapUtils;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * @author yinsi
 */

public class HttpFile {

    //图片压缩之后保存的路径
    private static final String compressPath = Environment.getExternalStorageDirectory().getAbsolutePath()
            + Key.PATH_LOCAL_IMAGE_COMPRESS;
    //----
    private static Handler handler = new Handler(Looper.getMainLooper());

    public static abstract class HttpCallBack {
        //开始
        public void onstart() {
        }

        //成功回调
        public abstract void onSusscess(String data);

        //成功回调
        public void onSusscess(ResponseBody data) {
        }


        //失败
        public void onError(String meg) {
        }
    }


    /**
     * post上传图片（带压缩）
     *
     * @param activity
     * @param interfaceName
     * @param map
     * @param fileList
     * @param callBack
     */
    public static void upload(Activity activity, String interfaceName, Map<String, String> map, List<String> fileList, boolean needCompress, final HttpCallBack callBack) {
        // ----
        MultipartBody.Builder body_builder = new MultipartBody.Builder();
        body_builder.setType(MultipartBody.FORM);
        //遍历map,添加键值对
        if (map != null) {
            for (Map.Entry<String, String> entry : map.entrySet()) {
                body_builder.addFormDataPart(entry.getKey(), entry.getValue().toString());
            }
        }
        //遍历图片，添加图片
        if (null != fileList && fileList.size() > 0) {
            for (int i = 0; i < fileList.size(); i++) {
                String path = "";
                if (needCompress) {
                    //压缩
                    path = BitmapUtils.compress(activity,
                            fileList.get(i), compressPath);
                } else {
                    path = fileList.get(i);
                }
                body_builder.addFormDataPart("upload",
                        path.substring(path.lastIndexOf("/")), RequestBody
                                .create(MediaType.parse("multipart/form-data"), new File(path)));
            }
        }
        Request.Builder request = new Request.Builder();
        request.url((Constants.isTest ? Constants.TestUrl : Constants.BaseUrl) + interfaceName);
        request.post(body_builder.build());
        OkHttpManager.getInstance().newCall(request.build()).enqueue(new Callback() {
            @Override
            public void onFailure(okhttp3.Call call, final IOException e) {
                OnError(callBack, e.getMessage());
            }

            @Override
            public void onResponse(okhttp3.Call call, final Response response) throws IOException {
                String data = response.body().string();
                if (response.isSuccessful()) {
                    onSuccess(callBack, data);
                } else {
                    OnError(callBack, response.message());
                }
            }
        });
    }

    /**
     * 请求接口成功
     *
     * @param callBack
     * @param data
     */
    private static void onSuccess(final HttpCallBack callBack, final String data) {
        if (callBack != null) {
            handler.post(new Runnable() {
                @Override
                public void run() {//在主线程操作
                    callBack.onSusscess(data);
                }
            });
        }
    }

    /**
     * 请求接口失败或返回失败
     *
     * @param callBack
     * @param msg
     */
    private static void OnError(final HttpCallBack callBack, final String msg) {
        if (callBack != null) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    callBack.onError(msg);
                }
            });
        }
    }

    public interface ProgressListener {
        /**
         * @param progress     已经下载或上传字节数
         * @param total        总字节数
         * @param done         是否完成
         */
        void onProgress(long progress, long total, boolean done);
    }

}
